﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Authorization.Verification
{
    public class PhoneMapper
    {
        private Dictionary<string, PhoneUnit> map = new Dictionary<string, PhoneUnit>();

        public void Add(string phoneNumber, string captcha)
        {
            map[phoneNumber] = new PhoneUnit
            {
                PhoneNumber = phoneNumber,
                Captcha = captcha,
                Time = DateTime.Now
            };

            if(map.Count > 10000)
            {
                RefreshMap();
            }
        }

        public bool CheckCaptcha(string phoneNumber, string captcha)
        {
            if(map.ContainsKey(phoneNumber))
            {
                if(map[phoneNumber].Captcha == captcha)
                {
                    return true;
                }
            }
            return false;
        }

        private void RefreshMap()
        {
            Dictionary<string, PhoneUnit> newMap = new Dictionary<string, PhoneUnit>();
            DateTime now = DateTime.Now;
            foreach (var item in map)
            {
                if (item.Value.Time.AddMinutes(5) > now)
                {
                    newMap[item.Key] = item.Value;
                }
            }
            map = newMap;
        }
    }

    public class PhoneUnit
    {
        public string PhoneNumber { get; set; }
        public DateTime Time { get; set; }
        public string Captcha { get; set; }
    }
}
